package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.UserForm;
import com.baseweb.webadmin.core.model.pojo.ByUserBizAuth;
import com.baseweb.webadmin.core.model.pojo.Role;
import com.baseweb.webadmin.core.model.pojo.User;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserService;
import net.sf.json.JSONObject;
import org.apache.poi.util.Internal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by dengsy on 2017-06-22.
 * 注册
 */
@Controller
@RequestMapping(value = "/registerWeb")
public class RegisterWebController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;


    /**
     * 手机短信验证
     */
    @RequestMapping(value = "/sendValidMsgWeb", method = RequestMethod.POST)
    public Map<String, Object> sendValidMsgWeb(@RequestParam(value = "mobile", required = true) String mobile){
        String code = CheckCodeUtil.newCheckCode(mobile);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("code", code);
        map.put("product", ConfigUtil.getSmsFreeSignName());
        boolean flag = CommonUtil.sendMessage(mobile, JSONObject
                .fromObject(map).toString(), ConfigUtil
                .getSmsTemplateCodeRegist());
        if (flag) {
            return success("短信发送成功");
        } else {
            return fail("短信发送失败");
        }
    }

    /**
     * 注册
     */
    @RequestMapping(value = "/bizTenantsMoreWeb", method = RequestMethod.POST)
    public String bizTenantsMoreWeb(HttpServletRequest request,@ModelAttribute()User user, Model model){
        /**
         * 查询该手机的用户是否已经注册了！
         */
        User userIsO = userService.selectByName(user.getUsername());

        /**
         * 手机号码和发送的手机验证码一致性验证
         */
        String result = CheckCodeUtil.verify(user.getUsername(), user.getValidate_code());
        /**
         * 如果发送的手机验证码与该手机不匹配，匹配标准，反馈是否为1 1表示一致。
         */
        if (Constants.IS_DEBUG || "1".equalsIgnoreCase(result)) {

            /**
             * 对该手机号码的查询结果进行判断。如果数据库存在
             */
            if (null != userIsO) {
                model.addAttribute("isOK", "NO");
                model.addAttribute("msg", "手机号码已被注册!");
            }else {
                String pw = user.getPassword();
                user.setPassword(MD5Util.Md5(pw.trim()));
                user.setToken(MD5Util.Md5(user.getPassword()+"boyi"+ DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                user.setStatus(7);
//                user.setUserType(UserType.NORMAL_USER.getCode());
                user.setCreateTime(new DateTime());
                user.setUpdateTime(new DateTime());
                user.setOrderCount(0);
                user.setCoins(50);
                user.setMoney(new BigDecimal("0.00"));
                user.setLevelCoins(0);
                user.setIsHot(0);
                user.setSex(0);
                user.setBizProductCount(0);
                user.setBizPrice(new BigDecimal("0.00"));

                if(userService.insertUser(user) == 1){
                    User userR = userService.selectByUserName(user.getUsername());
                    HttpSession session = request.getSession();
                    session.setAttribute("is_login", true);
                    session.setAttribute("login_name",user.getUsername());
                    session.setAttribute("login_id",user.getId());
                    session.setAttribute("login_type",user.getUserType());
                    if(userR.getUserType() == 2){
                        //写角色
                        //权限角色
                        roleService.insertIntoRoleUser(userR.getId(),3);
                        //职业角色
                        roleService.insertIntoRoleUser(userR.getId(),10);
                        //默认的佣金角色
                        roleService.insertIntoRoleUser(user.getId(),16);
                        //默认的信誉角色
                        roleService.insertIntoRoleUser(user.getId(),17);

                    }else if(userR.getUserType() == 3){
                        //写角色
                        //权限角色
                        roleService.insertIntoRoleUser(userR.getId(),4);
                        //职业角色
                        roleService.insertIntoRoleUser(userR.getId(),10);
                        //默认的佣金角色
                        roleService.insertIntoRoleUser(user.getId(),16);
                        //默认的信誉角色
                        roleService.insertIntoRoleUser(user.getId(),17);

                    }
                    model.addAttribute("isOK", "OK");
                    model.addAttribute("msg", "注册成功");
                }else {
                    model.addAttribute("isOK", "NO");
                    model.addAttribute("msg", "操作失败，请重试");
                }
            }
        }else{
            model.addAttribute("isOK","NO");
            model.addAttribute("msg", "手机验证码不正确!");
        }
        return "";
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "/systemUserInsertOrUpdate" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> systemUserInsertOrUpdate(HttpServletRequest request,UserForm userForm,Model model,
                                                        @RequestParam(value = "file", required = false) MultipartFile file){
        try{
            String isOK = "NO";
            HttpSession session = request.getSession();
            if(session.getAttribute("login_name") != null){
                User user = new User();
                user.setUsername(userForm.getUsername());
                user.setPassword(userForm.getPassword());
                user.setCnName(userForm.getCdName());
                user.setTrueName(userForm.getUnionName());
                user.setIdentity(userForm.getIdCard());
                user.setEmail(userForm.getEmail());
                user.setDescn(userForm.getDescn());
                user.setAddress(userForm.getAddress());
                user.setTagNames(userForm.getTagNames());
                user.setMobile(String.valueOf(session.getAttribute("login_name")));
                user.setBizDealCount(0);
                user.setBizStar("100%");
                user.setBizPrice(new BigDecimal("0.00"));
//                int loginType =Integer.valueOf(String.valueOf(session.getAttribute("login_type")));
//                if(loginType == 5){
//                    user.setBizAgentId(Integer.valueOf(String.valueOf(session.getAttribute("login_id"))));
//                }else {
//                    if(userForm.getAgentId() != null && !"".equals(userForm.getAgentId())){
//                        user.setBizAgentId(Integer.valueOf(userForm.getAgentId()));
//                    }
//                }
                if(userForm.getAgentId() != null && !"".equals(userForm.getAgentId())){
                    user.setBizAgentId(Integer.valueOf(userForm.getAgentId()));
                }
                //权限角色
                if(userForm.getDiction() !=null && !"".equals(userForm.getDiction())){
                    Role role = roleService.selectRoleById(Integer.valueOf(userForm.getDiction()));
                    if("001".equals(role.getCode())){
                        user.setUserType(1);
                    }else if("002".equals(role.getCode())){
                        user.setUserType(2);
                    }else if("003".equals(role.getCode())){
                        user.setUserType(3);
                    }else if("004".equals(role.getCode())){
                        user.setUserType(4);
                    }else if("005".equals(role.getCode())){
                        user.setUserType(5);
                    }else {
                        user.setUserType(1);
                    }
                }
                //省市区为空处理
                if("".equals(userForm.getS_province())){
                    user.setProvince(null);
                }else {
                    user.setProvince(userForm.getS_province());
                }
                if("".equals(userForm.getS_city())){
                    user.setCity(null);
                }else {
                    user.setCity(userForm.getS_city());
                }
                if("".equals(userForm.getS_county())){
                    user.setArea(null);
                }else {
                    user.setArea(userForm.getS_county());
                }

                //图片上传
                if (file != null && file.getSize() > 0){
                    String avatar_img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename()))+".jpg";

                    UploadUtil.uploadData(file.getBytes(), avatar_img_url);

                    user.setBizCover(avatar_img_url);
                    user.setAvatar(avatar_img_url);
                }

                if(userForm.getId() == null || "".equals(userForm.getId())){
                    /**
                     * 查询该手机的用户是否已经注册了！
                     */
                    User userIsO = userService.selectByName(user.getUsername());
                    if (null != userIsO) {
                        model.addAttribute("isOK", isOK);
                        model.addAttribute("msg", "手机号码已被注册!");
                    }else {
                        String pw = userForm.getPassword();
                        user.setPassword(MD5Util.Md5(pw.trim()));
                        user.setToken(MD5Util.Md5(user.getPassword()+"boyi"+ DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                        user.setStatus(7);
                        user.setCreateTime(new DateTime());
                        user.setUpdateTime(new DateTime());
                        user.setOrderCount(0);
                        user.setCoins(50);
                        user.setMoney(new BigDecimal("0.00"));
                        user.setLevelCoins(0);
                        user.setIsHot(0);
                        user.setSex(0);
                        user.setBizProductCount(0);

                        //写角色
                        int occupationId = 10;
                        int commistionId = 16;
                        int credibilityId = 17;
                        //职业角色
                        if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                            occupationId = Integer.parseInt(userForm.getOccupation());
                            if(occupationId == 11){
                                user.setBizWorkType(1);
                            }else if(occupationId == 12){
                                user.setBizWorkType(3);
                            }else if(occupationId == 13){
                                user.setBizWorkType(4);
                            }else if(occupationId == 14){
                                user.setBizWorkType(2);
                            }else if(occupationId == 15){
                                user.setBizWorkType(5);
                            }else {
                                user.setBizWorkType(999);
                            }
                        }

                        if(userService.insertUser(user) == 1){
                            User userR = userService.selectByUserName(user.getUsername());
                            //权限角色
                            if(userForm.getDiction() !=null && !"".equals(userForm.getDiction())){
                                roleService.insertIntoRoleUser(userR.getId(),Integer.parseInt(userForm.getDiction()));
                            }
                            //佣金角色
                            if(userForm.getCommission() != null && !"".equals(userForm.getCommission())){
                                commistionId = Integer.parseInt(userForm.getCommission());
                            }
                            //信誉角色
                            if(userForm.getCredibility() != null && !"".equals(userForm.getCredibility())){
                                credibilityId = Integer.parseInt(userForm.getCredibility());
                            }
                            roleService.insertIntoRoleUser(userR.getId(),occupationId);
                            roleService.insertIntoRoleUser(userR.getId(),commistionId);
                            roleService.insertIntoRoleUser(userR.getId(),credibilityId);
                            isOK = "OK";
                        } else {
                            model.addAttribute("msg", "添加用户基本资料失败!");
                        }
                    }
                }else {
                    user.setId(Integer.valueOf(userForm.getId()));
                    //职业角色
                    if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                        if(Integer.valueOf(userForm.getOccupation()) == 11){
                            user.setBizWorkType(1);
                        }else if(Integer.valueOf(userForm.getOccupation()) == 12){
                            user.setBizWorkType(3);
                        }else if(Integer.valueOf(userForm.getOccupation()) == 13){
                            user.setBizWorkType(4);
                        }else if(Integer.valueOf(userForm.getOccupation()) == 14){
                            user.setBizWorkType(2);
                        }else if(Integer.valueOf(userForm.getOccupation()) == 15){
                            user.setBizWorkType(5);
                        }else {
                            user.setBizWorkType(999);
                        }
                    }
                    if(userService.updateUser(user) == 1){
                        //修改角色
                        //权限角色
                        if(userForm.getDiction() !=null && !"".equals(userForm.getDiction())){
                            roleService.updateIntoRoleUser(Integer.parseInt(userForm.getDiction()),user.getId(),"1");
                        }
                        //职业角色
                        if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                            roleService.updateIntoRoleUser(Integer.parseInt(userForm.getOccupation()),user.getId(),"2");
                        }
                        //佣金角色
                        if(userForm.getCommission() != null && !"".equals(userForm.getCommission())){
                            roleService.updateIntoRoleUser(Integer.parseInt(userForm.getCommission()),user.getId(),"3");
                        }
                        //信誉角色
                        if(userForm.getCredibility() != null && !"".equals(userForm.getCredibility())){
                            roleService.updateIntoRoleUser(Integer.parseInt(userForm.getCredibility()),user.getId(),"4");
                        }
                        isOK = "OK";
                    }else {
                        model.addAttribute("msg", "修改用户基本资料失败!");
                    }
                }

                //用户搜索关键字授权
                if(!"".equals(userForm.getUserChannel())){
                    String[] userChannels=userForm.getUserChannel().split(",");
                    int userId = 0;
                    if(userForm.getId() == null || "".equals(userForm.getId())){
                        User userR = userService.selectByUserName(userForm.getUsername());
                        userId = userR.getId();
                    }else {
                        userId = Integer.valueOf(userForm.getId());
                    }
                    //删除已有
                    userService.deleteUserChannelByUserId(userId);
                    for(int i=0;i<userChannels.length;i++){
                        userService.insertIntoUserChannel(userId,Integer.valueOf(userChannels[i]));
                    }
                }

                model.addAttribute("isOK", isOK);
            }else {
                model.addAttribute("isOK", isOK);
                model.addAttribute("msg", "登录超时不能操作!");
            }
            return success(isOK);
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("isOK", "NO");
            model.addAttribute("msg", "系统异常，请重试");
            return success(null);
        }
    }

    /**
     * 商家注册详细资料
     */
    @RequestMapping(value = "/submitBizTenantsDetailWeb" , method = RequestMethod.POST)
    public String submitBizTenantsDetailWeb(@ModelAttribute()UserForm userForm,
                                            HttpServletRequest request, HttpServletResponse response,
                                            Model model,
                                            RedirectAttributes redirectAttributes) {
        try{
            String isOK = "NO";
            HttpSession session = request.getSession();
            if(session.getAttribute("login_name") != null){
                String userName = String.valueOf(session.getAttribute("login_name"));
                User user = userService.selectByName(userName);
                user.setCnName(userForm.getUnionName());
                user.setProvince(userForm.getS_province());
                user.setCity(userForm.getS_city());
                user.setArea(userForm.getS_county());

                if(userService.updateUser(user) != 1){
                    model.addAttribute("msg", "操作失败，请重试");
                }else {
                    writeCoinsLog(user, CoinType.REGISTER.getCode(),50);
                    //写角色
                    //权限角色
                    if(userForm.getDiction() !=null && !"".equals(userForm.getDiction())){
                        if(roleService.updateIntoRoleUser(Integer.parseInt(userForm.getDiction()),user.getId(),"1") == 1){
                            //职业角色
                            if(userForm.getOccupation() != null && !"".equals(userForm.getOccupation())){
                                if(roleService.updateIntoRoleUser(Integer.parseInt(userForm.getOccupation()),user.getId(),"2") == 1){

                                    isOK = "OK";
                                }else {
                                    model.addAttribute("msg", "职业角色操作失败，请重试");
                                }
                            }
                        }else {
                            model.addAttribute("msg", "权限角色操作失败，请重试");
                        }
                    }
                }
            }

            model.addAttribute("isOK", isOK);
            return "";
        }catch (Exception ex){
            ex.printStackTrace();
            model.addAttribute("isOK", "NO");
            model.addAttribute("msg", "系统异常，请重试");
            return "";
        }

    }
}
